<?php

namespace RTSCraft\MainBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

use RTSCraft\MainBundle\Controller\Util\AuthUtil;

class MainFrameController extends Controller
{
    /**
     * @Route("/", name="mainFrame")
     * @Template()
     */
    public function indexAction()
    {
      // index page
      $is_auth = (AuthUtil::is_auth($this) == 0 ? true : false);

	// Generate the "tree" :
    $tree = array("Factions" => $this->summarizeNames($this->getFactions()),
		  "Resources" => $this->summarizeNames($this->getResources()),
		  "Statistics" => $this->summarizeNames($this->getStatistics()));

    foreach ($this->getCategories() as $c)
      {
	$tree[$c->getName()] = $this->summarizeNames($this->getElementsByName($c->getName()));
      }

      return $this->render('RTSCraftMainBundle:Default:mainFrame.html.twig', array('is_auth' => $is_auth, 'render' => 'home', 'tree' => $tree));
    }

public function getResources()
  {
    $repo = $this->getDoctrine()->getRepository('RTSCraftMainBundle:Ressources');
    
    $results = $repo->findBy(array("deleted" => false));
    
    return $results;
  }
  
  public function getCategories()
  {
    $repo = $this->getDoctrine()->getRepository('RTSCraftMainBundle:Category');
    
    $results = $repo->findBy(array("deleted" => false));
      
    return $results;
  }

  public function getCategoryByName($n)
  {
    $repo = $this->getDoctrine()->getRepository('RTSCraftMainBundle:Category');
    
    $result = $repo->findByName($n);
      
    return $result[0];
  }

  public function getFactions()
  {
    $repo = $this->getDoctrine()->getRepository('RTSCraftMainBundle:Factions');
    
    $results = $repo->findBy(array("deleted" => false));
      
    return $results;
  }

  public function getStatistics()
  {
    $repo = $this->getDoctrine()->getRepository('RTSCraftMainBundle:Statistics');
    
    $results = $repo->findBy(array("deleted" => false));
      
    return $results;
  }

  public function getElementsByName($n)
  {
    $repo = $this->getDoctrine()->getRepository('RTSCraftMainBundle:Element');
    
    $results = $repo->findByCategory($n);
    return $results;
  }

  // Returns a list of the names of the given object list, or pushes them in the second agrument if it exists.
  protected function summarizeNames($list, $arr = null)
  {
    if ($arr != null)
      $res = $arr;
    else
      $res = array();
    foreach ($list as $e)
      {
	array_push($res, $e->getName());
      }
    return $res;
  }
}
